const multer = require('koa-multer');

// 配置存储
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, '../files/'); // 存储到项目根目录下的 files 文件夹
  },
  filename: function (req, file, cb) {
    const fileFormat = (file.originalname.split('.'));
    cb(null, Date.now() + '.' + fileFormat[fileFormat.length - 1]);
  }
});

const upload = multer({ storage: storage });

exports.uploadFile = upload.single('file');

exports.handleUpload = async (ctx) => {
  if (!ctx.req.file) {
    ctx.status = 400;
    ctx.body = { error: 'File is required' };
    return;
  }
  // 返回文件访问URL
  const fileUrl = `/files/${ctx.req.file.filename}`;
  ctx.body = { url: fileUrl };
};